// 暴露密码数据统一管理接口
// 支持 添加多个扩展
function genPromise(func = () => {}, params = { a: 3 }) {
  return new Promise((resolve) => {
    func(resolve, params)
  })
}

function filterFunc(funcs = [], key = '') {
  return funcs.filter(_ => typeof _[key] === 'function').map(_ => _[key].bind(_))
}

function promiseAll(funcs = [], next = () => {}, data) {
  // TODO: 根据 pluginKey 标识返回的 results
  Promise.all(funcs.map(f => genPromise(f, data))).then(results => next(results))
}

class DataManager {
  constructor() {
    this.plugins = []
    this.inits = []
  }
  init() {
    return new Promise((resolve) => {
      if (this.inits.length === 0) {
        resolve()
        return
      }
      Promise.all(this.inits).then(resolve)
    })
  }
  use(plugin = {}) {
    // eslint-disable-next-line no-param-reassign
    plugin.pluginKey = DataManager.getPluginKey(plugin)
    this.plugins.push(plugin)
    try {
      const initPromise = plugin.init() // plugins.init must be a promise, TODO: fix compatible
      this.inits.push(initPromise)
    } catch (err) {
      console.log(err)
    }
  }
  get(data = {}) {
    return this.genFunctions('get', data)
  }
  save(data = {}) {
    return this.genFunctions('save', data)
  }
  update(data = {}) {
    return this.genFunctions('update', data)
  }
  genFunctions(method, data) {
    return new Promise((resolve) => {
      const funcs = filterFunc(this.plugins, method)
      promiseAll(funcs, resolve, data)
    })
  }
  static getPluginKey(plugin) {
    let key = ''
    try {
      if (plugin.key) {
        key = plugin.key
      } else if (plugin.constructor) {
        // class
        key = plugin.constructor.name
      } else if (typeof plugin === 'function') {
        // function
        key = plugin.name
      }
    } catch (err) {
      console.log(err)
    }
    return key
  }
}
export default new DataManager()
